package com.magicrule.car.systemManage.configClass.shiro;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

import com.magicrule.car.systemManage.configClass.redis.RedisUtil;

/**
 * 
 * 登陆尝试次数不能超过5次，超过了就得等120s
 * @author hebb
 *
 */
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

	// 声明一个缓存接口，这个接口是Shiro缓存管理的一部分，它的具体实现可以通过外部容器注入
	private RedisUtil redisUtil;

	public RetryLimitHashedCredentialsMatcher(RedisUtil redisUtil) {
		this.setHashAlgorithmName("MD5");
		this.setHashIterations(2);
		this.setStoredCredentialsHexEncoded(true);
		this.redisUtil = redisUtil;
	}

	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		String username = (String) token.getPrincipal();
		AtomicInteger retryCount = new AtomicInteger();
		Object count = redisUtil.get(username);
		if (count == null) {
			retryCount = new AtomicInteger(0);
			redisUtil.set(username, retryCount, 120);
		} else {
			retryCount = (AtomicInteger) count;
			// 自定义一个验证过程：当用户连续输入密码错误5次以上禁止用户登录一段时间
			if (retryCount.incrementAndGet() > 5) {
				throw new ExcessiveAttemptsException();
			}
		}

		boolean match = super.doCredentialsMatch(token, info);
		if (match) {
			redisUtil.del(username);
		}

		return match;

	}
}